<?php
declare (strict_types = 1);

namespace app\admin\controller\erp;

use app\admin\controller\AuthController;
use app\admin\model\erp\ErpSubjects;
use app\admin\model\erp\ErpVoucher;
use app\admin\model\erp\ErpVoucherPeriod;
use app\admin\model\system\SystemMenus;
use think\facade\Config;
use think\facade\Db;
use think\Request;

/*
 * 初始数据
 */
class InitialData extends AuthController
{
    /**
     * 显示列表
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function index(Request $req)
    {
        $erp_initial = Config::get('erp.erp_initial',['period'=>'202100','period_code'=>'2021000001']);
        $period = $erp_initial['period'];
        $list = Db::name('erp_subjects')->alias('a')
            ->leftJoin('erp_voucher b', "b.period='{$period}' AND b.code LIKE CONCAT(a.code,'%')")
            ->group('a.code')
            ->order('a.level ASC,a.id ASC')
            ->field('a.id,a.pid,a.code,a.name,a.pname,a.level,ifnull(ROUND(SUM(b.debit),2),0.00) as debit,ifnull(ROUND(SUM(b.credit),2), 0.00) as credit')->select()->toArray();
        //echo Db::getLastSql();
        $luck = ErpVoucherPeriod::where('period','=',$period)->max('luck');
        $data = [];
        $debit = Db::name('erp_voucher')->where('period','=',$period)->sum('debit');
        $credit = Db::name('erp_voucher')->where('period','=',$period)->sum('credit');
        $data[] = ['id'=>'a','pid'=>0,'name'=>'合计：','code'=>'','debit'=>round($debit,2),'credit'=>round($credit,2),'son'=>1,'luck'=>$luck];
        foreach($list as $val) {
            $val['son'] = 0;
            $val['luck'] = $luck;
            $data[$val['id']] = $val;
            if(isset($data[$val['pid']])) $data[$val['pid']]['son'] = 1;
        }
        $sonAuth = SystemMenus::getSonAuth($req->controller(), $req->action(),array_keys($this->auth));
        // 显示页面
        $this->assign('sonAuth', $sonAuth);
        $this->assign('data', $data);
        $this->assign('luck', $luck);
        return $this->fetch();
    }

    /**
     * 更新资源
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function edit(Request $req)
    {
        if($req->isPost()) {
            $code = $req->param('code/d', 0);
            $debit = $req->param('debit/f', 0);
            $credit = $req->param('credit/f', 0);
            if(!$code) $this->error('参数错误：缺少科目编码');
            $erp_initial = Config::get('erp.erp_initial',['period'=>'202100','period_code'=>'2021000001']);
            $period = $erp_initial['period'];
            $period_code = $erp_initial['period_code'];
            $time = time();
            $sub = ErpSubjects::where('code','=',$code)->find();
            if(!$sub) $this->error('参数错误：科目不存在');
            $period_data = ErpVoucherPeriod::where('period','=',$period)->where('period_code','=',$period_code)->find();
            if(!$period_data) {
                $info = [
                    'period'        => $period,//凭证期间
                    'period_code'   => $period_code,//凭证号
                    'description'   => '期初数据',//摘要
                    'market'        => '',//备注
                    'create_at'     => $time,//
                    'update_at'     => $time
                ];
                $res = ErpVoucherPeriod::create($info);
                if (!$res) {
                    $this->error('凭证主表存入失败！');
                }
            } else {
                if($period_data['luck'] == 1) $this->error('期初数据已锁帐！');
            }
            $voucher = ErpVoucher::where('period','=',$period)->where('period_code','=',$period_code)->where('code','=',$code)->find();
            if($voucher) {
                if($voucher['debit'] == $debit && $voucher['credit'] == $credit) $this->error('数据无变化！');
                $info = [
                    'debit'     => $debit,
                    'credit'    => $credit,
                    'update_at' => $time
                ];
                $res = ErpVoucher::where('id','=',$voucher['id'])->update($info);
                if (!$res) {
                    $this->error('修改失败！');
                }
            } else {
                $info = [
                    'period'        => $period,//凭证期间
                    'period_code'   => $period_code,//凭证号
                    'code'          => $code,
                    'code_name'     => $sub['code'].'-'.$sub['name'],
                    'debit'         => $debit,
                    'credit'        => $credit,
                    'period_at'     => 0,//
                    'create_at'     => $time,//
                    'update_at'     => $time
                ];
                $res = ErpVoucher::create($info);
                if (!$res) {
                    $this->error('修改失败！');
                }
            }
            $this->success();
        }
    }

    /**
     * 锁帐/反锁帐
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function luck(Request $req)
    {
        if($req->isAjax()) {
            $erp_initial = Config::get('erp.erp_initial',['period'=>'202100','period_code'=>'2021000001']);
            $period = $erp_initial['period'];
            $period_data = ErpVoucherPeriod::where('period', $period)->find();
            if (!$period_data) $this->error('参数错误');

            $luck = $period_data['luck'] ? 0 : 1;
            $res = ErpVoucherPeriod::where('period','=',$period)->update(
                [
                    'luck' => $luck,
                    'update_at' => time(),
                ]
            );
            if($res) {
                $this->success();
            } else {
                $this->error();
            }
        }
    }
}
